package com.eclipsemail.core.reader.impl;

import java.util.List;
import java.util.Properties;

import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Store;

import com.eclipsemail.core.authentication.Authenticable;
import com.eclipsemail.core.authentication.AuthenticationException;
import com.eclipsemail.core.message.EmailMessage;
import com.eclipsemail.core.reader.ReaderMail;
import com.eclipsemail.core.reader.utils.ParserMessage;
import com.google.common.collect.Lists;

public class GMailReader implements ReaderMail {

    @Override
    public List<EmailMessage> getInbox(Authenticable authentication) throws AuthenticationException {
        return getEmails(authentication, "inbox");
    }

    @Override
    public List<EmailMessage> getEmails(Authenticable authentication, String folderName) throws AuthenticationException {
        List<EmailMessage> msgs = Lists.newArrayList();

        // open the session
        Session session = Session.getDefaultInstance(new Properties(), null);
        Store store = authentication.connect(session);
        try {
            try {
                // open de mail inbox
                Folder folder = null;
                folder = store.getFolder(folderName);
                folder.open(Folder.READ_ONLY);
                try {
                    // le e adiciona todas as msgs no array
                    Message[] messages = folder.getMessages();
                    for (Message msg : messages) {
                        msgs.add(ParserMessage.convert(msg));
                    }
                } finally {
                    folder.close(true);
                }
            } finally {
                store.close();
            }
        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }

        return msgs;
    }

}
